<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>选题管理</el-breadcrumb-item>
      <el-breadcrumb-item>题目列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 我的选题 -->
    <el-card class="myCard">
      <el-alert title="我的题目" type="info" show-icon></el-alert>
      <el-table :data="title" border>
        <!-- 展开行 -->
        <el-table-column type="expand" label="展开详细内容" width="120">
          <template slot-scope="scope">
            <el-input
              type="textarea"
              :rows="5"
              placeholder="请输入内容"
              v-model="scope.row.content1"
              readonly
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="指导老师" prop="teacher1"></el-table-column>
        <el-table-column label="题目" prop="title1"></el-table-column>
        <el-table-column label="操作" v-if="title[0].title1 !== ''">
          <template slot-scope="scope">
            <!-- 修改志愿按钮 -->
            <el-button
              icon="el-icon-edit"
              size="mini"
              type="warning"
              @click="showAddDialog(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 表格展示题目 -->
      <el-table :data="articleList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <!-- 展开行 -->
        <el-table-column type="expand" label="展开内容" width="80">
          <!-- 展开后作用域插槽 -->
          <template slot-scope="scope">
            <el-row>
              <el-col :span="2">
                <el-tag type="success">设计内容：</el-tag>
              </el-col>
              <el-col :span="12">
                <el-input
                  type="textarea"
                  :rows="10"
                  placeholder="请输入内容"
                  v-model="scope.row.content"
                  readonly
                ></el-input>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="_id" label="题目id"></el-table-column>
        <el-table-column prop="title" label="题目名称"></el-table-column>
        <el-table-column
          prop="Tauthor.username"
          label="指导老师"
        ></el-table-column>
        <el-table-column
          prop="Tauthor.email"
          label="指导老师邮箱"
        ></el-table-column>
        <el-table-column prop="publishDate" label="发布时间">
          <!-- 发布时间作用域插槽 -->
          <template slot-scope="scope">{{
            scope.row.publishDate | dateFormat
          }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="success"
              icon="el-icon-setting"
              @click="select(scope.row._id)"
              size="mini"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 修改志愿对话框 -->
      <el-dialog
        title="修改"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="resetAddForm"
      >
        <!-- 修改表单 -->
        <el-form
          :model="addForm"
          :rules="addRules"
          ref="addFormRef"
          label-width="100px"
          label-position="top"
        >
          <!-- 指导老师 -->
          <el-form-item label="指导老师" prop="teacher1">
            <!-- 选择器 -->
            <el-select
              v-model="addForm.teacher1"
              placeholder="请选择"
              @change="TselectChange"
            >
              <el-option
                v-for="(item, index) in teacherList"
                :key="index"
                :label="item.username"
                :value="item._id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题目 -->
          <el-form-item label="题目" prop="title1">
            <!-- 选择器 -->
            <el-select v-model="addForm.title1" placeholder="请选择">
              <el-option
                v-for="(item, index) in articleListFromTec"
                :key="index"
                :label="item.title"
                :value="item._id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addTitle">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      total: 0,
      // 题目列表
      articleList: [],
      // 指导老师列表
      teacherList: [],
      // 指定指导老师的题目列表
      articleListFromTec: [],
      // 当前登陆学生的题目
      title: [
        {
          teacher1: '',
          title1: '',
          content1: ''
        }
      ],
      // 控制对话框显示与否
      addDialogVisible: false,
      // 修改题目表单
      addForm: {
        teacher1: '',
        title1: ''
      },
      // 表单验证规则
      addRules: {
        teacher1: [
          { required: true, message: '请选择指导老师', trigger: 'blur' }
        ],
        title1: [{ required: true, message: '请选择题目', trigger: 'blur' }]
      },
      // 当前登陆学生的id
      id: ''
    }
  },
  // 生命周期函数，等dom元素加载完就会执行
  mounted() {
    // 获取当前登陆学生的id
    this.id = this.$store.state.uid
  },
  created() {
    // 获取文章列表
    this.getArticleList()
    // 获取学生题目
    this.getTitle()
  },
  methods: {
    // 获取题目列表
    async getArticleList() {
      const { data: res } = await this.$http.get('articles', {
        params: this.queryInfo
      })
      // 判断请求结果
      if (res.meta.status !== 200) {
        return this.$message.error('获取题目列表失败')
      }
      // 请求成功
      // 1 先为下方大表格的题目列表赋值
      // 2 过滤出已经通过审核的题目
      let result1 = res.data.records
      // 3 过滤
      result1 = result1.filter(item => {
        return item.checked === true
      })
      // 4 赋值
      this.articleList = result1

      this.total = res.data.total
      console.log(this.articleList)

      // 5 后为上方我的题目的添加表单里下拉框对应老师的题目数据赋值
      // 6 过滤出Tauthor._id的值等于this.addForm.teacher1的数据
      // 7 还有过滤得出对应指导老师的“已被审核”题目
      let result2 = res.data.records
      result2 = result2.filter(item => {
        return (
          item.Tauthor._id === this.addForm.teacher1 && item.checked === true
        )
      })
      this.articleListFromTec = result2
      console.log(this.articleListFromTec)
    },

    // 获取当前登陆学生的题目
    async getTitle() {
      // 获取学生id
      const uid = this.$store.state.uid
      const { data: res } = await this.$http.get('users/' + uid)
      // 判断请求结果
      if (res.meta.status !== 200) {
        return this.$message.error('获取学生题目失败')
      }
      // 请求成功,给title数组赋值,因为需要渲染到table表格中，所以需用数组保存数据
      console.log(res.data)
      if (res.data.title1) {
        this.title[0].teacher1 = res.data.title1.Tauthor.username
        this.title[0].title1 = res.data.title1.title
        this.title[0].content1 = res.data.title1.content
      }
      console.log(this.title)
    },
    // 获取指导老师列表
    async getTeacherList() {
      // 发送请求，获取指导老师列表
      const { data: res } = await this.$http.get('users', {
        params: { query: 'teacher' }
      })
      // 请求成功后赋值
      this.teacherList = res.records
      console.log(this.teacherList)
    },
    // 每页显示条数改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      // 重新获取题目列表
      this.getArticleList()
    },
    // 当前页码改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      // 重新获取题目列表
      this.getArticleList()
    },
    // 显示对话框
    showAddDialog(row) {
      this.getTeacherList()
      this.addDialogVisible = true
    },
    // 指导老师选择器change事件
    TselectChange() {
      // 获取题目列表
      this.getArticleList()
      console.log(this.addForm.titles)
    },
    // 确定提交志愿
    addTitle() {
      // 预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('验证未通过')
        }
        // 验证通过
        console.log(this.addForm)
        // 发送请求.添加到数据库
        const { data: res } = await this.$http.post(
          'students/select/' + this.id,
          {
            title1: this.addForm.title1
          }
        )
        // 判断请求结果
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        // 请求成功,给出提示
        this.$message.success('修改成功')
        // 重新获取列表
        this.getTitle()
        this.addDialogVisible = false
      })
    },
    // 对话框关闭事件
    resetAddForm() {
      this.$refs.addFormRef.resetFields()
    },

    // 选择志愿
    async select(id) {
      const confirmResult = await this.$confirm(
        '确定选择此题目, 是否继续?',
        '提示:重复选择会覆盖上一次的选择',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果点击了取消
      if (confirmResult === 'cancel') {
        return this.$message.info('已经取消了选择')
      }
      // 否则就发送请求，添加志愿
      const { data: res } = await this.$http.post(
        'students/select/' + this.id,
        { title1: id }
      )
      // 判断请求结果
      if (res.meta.status !== 200) {
        return this.$message.error('选择失败')
      }
      // 请求成功，给出提示
      this.$message.success('选择成功')
      // 重新获取学生题目
      this.getTitle()
    }
  }
}
</script>

<style lang="less" scoped>
.myCard {
  margin-bottom: 15px;
}
</style>
